//
//  XLRCIMDataSource.m
//  XLBaseModule
//
//  Created by 于鹏 on 2017/9/12.
//  Copyright © 2017年 YIVIEW. All rights reserved.
//

#import "XLRCIMDataSource.h"
#import "XLRCIMDataBaseManager.h"
#import "XLUserInfo.h"
#import "XLHTTPRequest.h"
@implementation XLRCIMDataSource

+ (XLRCIMDataSource *)shareInstance {
    static XLRCIMDataSource *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[XLRCIMDataSource alloc]init];
    });
    return instance;
}

#pragma mark - RCIMUserInfoDataSource
- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *))completion {
    if ([userId isEqualToString:[RCIM sharedRCIM].currentUserInfo.userId]) {
        RCUserInfo *myselfInfo = [[RCUserInfo alloc]initWithUserId:[RCIM sharedRCIM].currentUserInfo.userId name:[RCIM sharedRCIM].currentUserInfo.name portrait:[RCIM sharedRCIM].currentUserInfo.portraitUri];
        completion(myselfInfo);
        
    }else{
        //先从数据库中查找
        RCUserInfo *userInfo = [[XLRCIMDataBaseManager shareInstance] getUserByUserId:userId];
        if (userInfo) {
            completion(userInfo);
        } else {
            //请求
            NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
            [parameters setValue:userId forKey:@"RY_ID"];
            [parameters setValue:UserInfo.userID  forKey:@"DoctorID"];
            [parameters setValue:UserInfo.tokenCode forKey:@"TokenCode"];
            [XLHTTPRequest Doctor_searchDoctorByRYIDWithParameters:parameters success:^(id responseObject) {
                NSDictionary *dic = responseObject[@"_info"];
                
                NSString *nickName = [NSString stringWithFormat:@"%@",dic[@"DoctorNickName"]];
                NSString *user_logo = [UserInfo.serviceInfo.baseURL stringByAppendingString:[NSString stringWithFormat:@"%@",dic[@"DoctorHeaderLogo"]]];
                
                RCUserInfo *user = [[RCUserInfo alloc] init];
                user.userId = userId;
                user.name = nickName;
                user.portraitUri = user_logo;
                if (user) {
                    //插入数据库
                    [[XLRCIMDataBaseManager shareInstance]insertUserToDB:user];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        completion(user);
                    });
                }
            } failure:^(NSError *error, NSString *info) {
                completion(nil);
            }];
            
        }
    }
}

@end
